import { GlobalData } from '/store/state'
import { $event } from '/utils'
import { getServer } from '/store/mutations'
import { activityApi } from '/api/activity'

Page({
  data: {
    currentTab: 0,
    navigationHeight: GlobalData.navigationHeight,
    navData: [{ isLastpage: false }, { isLastpage: false }, { isLastpage: false }],
    list: [[] as Activity[]],
    user: {} as DomoUser,
    nav: ['发布的', '感兴趣', '想参加'],
  },
  async onLoad() {
    $event.on('after:boot', this, () => {
      this.setData({
        navigationHeight: GlobalData.navigationHeight,
        user: wx.getStorageSync(`${getServer()}/logged`).data,
      })
    })
    this.setData!({
      navigationHeight: GlobalData.navigationHeight,
      user: wx.getStorageSync(`${getServer()}/logged`).data,
    })
    this.onPullDownRefresh()
    $event.on('after:eventChange', this, () => {
      this.onPullDownRefresh()
    })
  },
  // tab切换
  clickTab(e: WechatMiniprogram.CustomEvent) {
    const {
      data: { list, currentTab },
    } = this
    const index = e.currentTarget.dataset.current
    if (currentTab === index) return
    this.setData({
      currentTab: +index,
    })
    if (list[index]) return
    this.getData()
  },
  /** 获取数据 */
  async getData(isLoadMore = false) {
    const {
      data: { navData, currentTab: cur, list, user },
    } = this
    if (isLoadMore && navData[cur].isLastpage) {
      wx.showToast({
        title: '已没有更多数据',
        icon: 'none',
        duration: 1000,
      })
      return
    }
    if (isLoadMore) {
      wx.showLoading({
        title: '加载中',
      })
    }

    const methods = cur === 0 ? 'getActivityList' : cur === 1 ? 'getLikedList' : 'getWantJoinList'
    const lists = await activityApi[methods]({
      offset: isLoadMore && list[cur] ? list[cur].length : 0,
      user_id: user.id,
      limit: 15,
      with: 'event',
    })
    /** 洗数据,fitler防止活动被删除后后端返回null */
    const datas =
      cur > 0
        ? lists
          .map((item) => {
            return item.event
          })
          .filter((i) => {
            return i !== null
          })
        : lists
    this.setData({
      [`list[${cur}]`]: isLoadMore && list[cur] ? [...list[cur], ...datas] : datas,
      [`navData[${cur}].isLastpage`]: lists.length < 15,
    })
    wx.hideLoading()
  },
  async onReachBottom() {
    this.getData(true)
  },
  async onPullDownRefresh() {
    await this.getData()
    wx.stopPullDownRefresh()
  },
})
